/**
 * Parse string to Customer object
 * String format:Customer Code;Type;Primary	contact;Name;Address;
 */
package data.converter.parser;

import java.util.ArrayList;
import java.util.HashMap;

import data.converter.model.Address;
import data.converter.model.Customer;
import data.converter.model.Person;

public class ParserToCustomer {

	private HashMap<String,String> mapping = new HashMap<String, String>();
	private String[] names = {
			"customerCode","type", "primaryContact", "name", "address"
	};
	private ParserToAddress mappingToAddress = new ParserToAddress();
	private ArrayList<Person> personList;
	
	public void setPersonList(ArrayList<Person> personList) {
		this.personList = personList;
	}
	
	/**
	 * @param strValue Follow the "String format" strictly
	 * @return customer
	 */
	public Customer converterToCustomer(String strValue) {
		String[] items = strValue.split(";");
		for(int i=0; i < names.length; i++) {
			mapping.put(names[i], items[i] == null ? "" : items[i]);
		}
		Customer customer = new Customer();
		Address address = mappingToAddress.convertToAddress((mapping.get("address")));
		customer.setAddress(address);
		customer.setCustomerCode(mapping.get("customerCode"));
		customer.setName(mapping.get("name"));
		customer.setType(mapping.get("type").charAt(0));
		String consultantCode = mapping.get("primaryContact");
		customer.setPrimaryContact(searchPerson(consultantCode));
		return customer;
	}
	
	/**
	 * @param personCode
	 * @return person
	 * Search person by personCode from personList,
	 * and personList gets from Person.dat
	 */
	private Person searchPerson(String personCode) {
		if(personList == null || personList.isEmpty()) {
			return null;
		}
		for(Person person: personList) {
			if(personCode.equals(person.getPersonCode())) {
				return person;
			}
		}
		return null;
	}
}
